<template>
  <div class="customer-container">
    <!-- 查询 -->
    <div class="search-container">
      <el-input
          placeholder="请输入客户姓名/ID"
          style="width: 200px"
          v-model="queryKeyword"
          class="search-input"
          clearable
          @keyup.enter="queryPreferences"
      ></el-input>
      <el-button
          @click="queryPreferences"
          type="success"
          plain
          class="search-button"
          :loading="loading"
      >
        查询
      </el-button>
      <el-button
          @click="showPreferenceDialog"
          type="primary"
          class="register-button"
      >
        新增客户喜好
      </el-button>
    </div>

    <!-- 提示信息 -->
    <div v-if="tipMessage" class="tip-message">
      <el-alert :title="tipMessage" :type="tipType" show-icon />
    </div>

    <!-- 错误信息 -->
    <div v-if="errorMessage" class="error-message">
      <el-alert :title="errorMessage" type="error" show-icon />
    </div>

    <!-- 膳食喜好表格 -->
    <el-table
        :data="preferenceList"
        class="customer-table"
        header-cell-class-name="table-header"
        v-loading="loading"
        empty-text="暂无数据"
    >
      <el-table-column
          label="序号"
          type="index"
          width="60px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="customer_name"
          label="客户姓名"
          width="120px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="customer_id"
          label="客户ID"
          width="120px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="preferences"
          label="喜好"
          width="120px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="attention"
          label="注意事项"
          width="150px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="remark"
          label="备注"
          width="200px"
          align="center"
      ></el-table-column>
      <el-table-column label="操作" width="220px" align="center">
        <template #default="scope">
          <el-button
              type="primary"
              size="small"
              @click="showDetailDialog(scope.row.id)"
              class="detail-button"
          >
            查看
          </el-button>
          <el-button
              type="primary"
              size="small"
              @click="showEditDialog(scope.row.id)"
              class="edit-button"
              :disabled="scope.row.isDeleted === 1"
          >
            修改
          </el-button>
          <el-button
              type="danger"
              size="small"
              @click="confirmDelete(scope.row.id)"
              class="delete-button"
              :disabled="scope.row.isDeleted === 1"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
          background
          v-model:current-page="pageContains.pageNum"
          v-model:page-size="pageContains.pageSize"
          :page-sizes="[10, 20, 30, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageContains.total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
          class="pagination"
          :disabled="loading"
      />
    </div>

    <!-- 膳食喜好对话框 -->
    <el-dialog
        v-model="preferenceDialog"
        :title="dialogTitle"
        class="customer-dialog"
        width="500px"
        :close-on-click-modal="false"
    >
      <el-form :model="curPreference" class="customer-form" :rules="rules" ref="preferenceForm">
        <el-form-item label="客户ID" prop="customer_id" class="form-item">
          <el-input
              placeholder="输入客户ID"
              v-model="curPreference.customer_id"
              @change="getCustomerNameById"
              class="form-input"
              clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="客户姓名" class="form-item">
          <el-input
              v-model="curPreference.customer_name"
              :disabled="dialogOptType === 1 || dialogOptType === 2"
              class="form-input"
              readonly
          ></el-input>
        </el-form-item>
        <el-form-item label="喜好" prop="preferences" class="form-item">
          <el-input v-model="curPreference.preferences" class="form-input" placeholder="请输入客户饮食喜好"></el-input>
        </el-form-item>
        <el-form-item label="注意事项" prop="attention" class="form-item">
          <el-input v-model="curPreference.attention" class="form-input" placeholder="请输入注意事项"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark" class="form-item">
          <el-input v-model="curPreference.remark" class="form-input" placeholder="请输入备注信息"></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="closeDialog" class="dialog-button">取消</el-button>
        <el-button type="primary" @click="confirmOpt" class="dialog-button" :loading="submitting">{{ buttonOpt }}</el-button>
      </div>
    </el-dialog>

    <!-- 客户详细信息对话框 -->
    <el-dialog
        v-model="detailDialog"
        title="客户详细信息"
        class="customer-detail-dialog"
        width="500px"
    >
      <el-form :model="curDetail" class="customer-detail-form" label-width="120px">
        <el-form-item label="客户ID">
          <el-input v-model="curDetail.customer_id" readonly></el-input>
        </el-form-item>
        <el-form-item label="客户姓名">
          <el-input v-model="curDetail.customer_name" readonly></el-input>
        </el-form-item>
        <el-form-item label="喜好">
          <el-input v-model="curDetail.preferences" readonly></el-input>
        </el-form-item>
        <el-form-item label="注意事项">
          <el-input v-model="curDetail.attention" readonly></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="curDetail.remark" readonly></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="closeDetailDialog" class="dialog-button">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import http from '@/axios/http';
import qs from "qs";
import { ElMessage, ElMessageBox } from 'element-plus';

// 膳食喜好数据集合（包含客户姓名）
let preferenceList = ref([]);
// 提示信息
let tipMessage = ref("");
let tipType = ref("info");
// 错误提示
let errorMessage = ref("");
// 搜索关键字（支持客户ID/姓名）
let queryKeyword = ref("");
// 对话框相关
let preferenceDialog = ref(false);
let curPreference = ref({
  customer_id: null,
  customer_name: '',
  preferences: '',
  attention: '',
  remark: ''
});
let dialogTitle = reactive("");
let buttonOpt = reactive("");
let dialogOptType = reactive(1); // 1:新增 2:编辑
// 分页信息
let pageContains = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
});
// 加载状态
let loading = ref(false);
// 提交状态
let submitting = ref(false);
// 表单验证
const preferenceForm = ref(null);
const rules = reactive({
  customer_id: [
    { required: true, message: '客户ID不能为空', trigger: 'blur' },
    { pattern: /^\d+$/, message: '请输入数字ID', trigger: 'blur' }
  ],
  preferences: [
    { required: true, message: '请输入客户喜好', trigger: 'blur' }
  ]
});

// 客户详细信息对话框相关
let detailDialog = ref(false);
let curDetail = ref({
  customer_id: null,
  customer_name: '',
  preferences: '',
  attention: '',
  remark: ''
});

// 获取膳食喜好列表（多表关联）
function queryPreferences() {
  loading.value = true;
  errorMessage.value = "";
  tipMessage.value = "";

  let params = {
    pageNum: pageContains.value.pageNum,
    pageSize: pageContains.value.pageSize,
    keyword: queryKeyword.value
  };

  http.post('/lyy/get_customer_preferences_with_name', qs.stringify(params))
      .then(res => {
        if (res.data.result === 'success') {
          pageContains.value = res.data.data;
          preferenceList.value = res.data.data.list;

          // 如果没有数据且是第一页，显示提示
          if (pageContains.value.total === 0 && pageContains.value.pageNum === 1) {
            tipMessage.value = "暂无膳食喜好数据，请添加";
            tipType.value = "info";
          }
        } else {
          errorMessage.value = res.data.error || "查询失败";
        }
      })
      .catch(error => {
        console.error('查询出错:', error);
        errorMessage.value = '网络请求出错，请稍后重试';
      })
      .finally(() => {
        loading.value = false;
      });
}

// 显示新增对话框
function showPreferenceDialog() {
  dialogTitle = "新增客户喜好";
  buttonOpt = "新增";
  dialogOptType = 1;
  curPreference.value = {
    customer_id: null,
    customer_name: '',
    preferences: '',
    attention: '',
    remark: ''
  };
  preferenceDialog.value = true;
  // 重置表单验证
  if (preferenceForm.value) {
    preferenceForm.value.resetFields();
  }
  // 设置新增时客户姓名字段禁用
  curPreference.value.customer_name = '';
}

// 根据客户ID获取客户姓名
function getCustomerNameById() {
  if (!curPreference.value.customer_id) {
    ElMessage.warning('请输入客户ID');
    return;
  }

  http.post('/lyy/get_customer_name_by_id_from_customer', qs.stringify({ id: curPreference.value.customer_id }))
      .then(res => {
        if (res.data.result === 'success') {
          curPreference.value.customer_name = res.data.data.customer_name;
        } else {
          ElMessage.error(res.data.error || '获取客户姓名失败');
          curPreference.value.customer_name = '';
        }
      })
      .catch(error => {
        ElMessage.error('网络请求出错，请稍后重试');
        console.error('获取客户姓名出错:', error);
      });
}

// 显示编辑对话框
function showEditDialog(id) {
  dialogTitle = "修改膳食喜好";
  buttonOpt = "修改";
  dialogOptType = 2;

  // 获取带客户姓名的详细信息
  http.post('/lyy/get_preference_by_id', qs.stringify({ id: id }))
      .then(res => {
        if (res.data.result === 'success') {
          curPreference.value = res.data.data;
          preferenceDialog.value = true;
        } else {
          ElMessage.error(res.data.error || '获取详细信息失败');
          console.error('获取详细信息出错:', res.data.error);
        }
      })
      .catch(error => {
        ElMessage.error('网络请求出错，请稍后重试');
        console.error('获取详细信息出错:', error);
      });
}

// 显示详细信息对话框
function showDetailDialog(id) {
  // 获取带客户姓名的详细信息
  http.post('/lyy/get_preference_by_id', qs.stringify({ id: id }))
      .then(res => {
        if (res.data.result === 'success') {
          curDetail.value = res.data.data;
          detailDialog.value = true;
        } else {
          ElMessage.error(res.data.error || '获取详细信息失败');
          console.error('获取详细信息出错:', res.data.error);
        }
      })
      .catch(error => {
        ElMessage.error('网络请求出错，请稍后重试');
        console.error('获取详细信息出错:', error);
      });
}

// 关闭详细信息对话框
function closeDetailDialog() {
  detailDialog.value = false;
}

// 确认操作
function confirmOpt() {
  preferenceForm.value.validate((valid) => {
    if (!valid) {
      ElMessage.warning('请填写完整信息');
      return false;
    }

    if (dialogOptType === 2) {
      confirmUpdate();
    } else {
      confirmAdd();
    }
  });
}

// 确认新增
function confirmAdd() {
  ElMessageBox.confirm('确定要新增此膳食喜好记录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    addPreference();
  }).catch(() => {
    ElMessage.info('已取消新增');
  });
}

// 确认修改
function confirmUpdate() {
  ElMessageBox.confirm('确定要修改此膳食喜好记录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    updatePreference();
  }).catch(() => {
    ElMessage.info('已取消修改');
  });
}

// 确认删除
function confirmDelete(id) {
  ElMessageBox.confirm('确定要删除此膳食喜好记录吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  }).then(() => {
    removeOne(id);
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
}

// 新增膳食喜好
function addPreference() {
  submitting.value = true;
  errorMessage.value = "";

  let param = {
    customerId: curPreference.value.customer_id,
    preferences: curPreference.value.preferences,
    attention: curPreference.value.attention,
    remark: curPreference.value.remark
  };

  http.post('/lyy/add_customer_preference', param)
      .then(res => {
        if (res.data.result === 'success') {
          ElMessage.success('新增成功');
          closeDialog();
          queryPreferences();
        } else {
          errorMessage.value = res.data.error || '新增失败';
          ElMessage.error(errorMessage.value);
        }
      })
      .catch(error => {
        errorMessage.value = '网络请求出错，请稍后重试';
        ElMessage.error(errorMessage.value);
        console.error('新增膳食喜好出错:', error);
      })
      .finally(() => {
        submitting.value = false;
      });
}

// 修改膳食喜好
function updatePreference() {
  submitting.value = true;
  errorMessage.value = "";

  let param = {
    id: curPreference.value.id,
    customerId: curPreference.value.customer_id,
    preferences: curPreference.value.preferences,
    attention: curPreference.value.attention,
    remark: curPreference.value.remark
  };

  http.post('/lyy/update_customer_preference', param)
      .then(res => {
        if (res.data.result === 'success') {
          ElMessage.success('修改成功');
          closeDialog();
          queryPreferences();
        } else {
          errorMessage.value = res.data.error || '修改失败';
          ElMessage.error(errorMessage.value);
        }
      })
      .catch(error => {
        errorMessage.value = '网络请求出错，请稍后重试';
        ElMessage.error(errorMessage.value);
        console.error('修改膳食喜好出错:', error);
      })
      .finally(() => {
        submitting.value = false;
      });
}

// 删除操作
function removeOne(id) {
  loading.value = true;
  errorMessage.value = "";

  http.post('/lyy/delete_preference_by_id', qs.stringify({ id: id }))
      .then(res => {
        if (res.data.result === 'success') {
          ElMessage.success('删除成功');
          // 如果当前页只有一条数据且不是第一页，则返回上一页
          if (preferenceList.value.length === 1 && pageContains.value.pageNum > 1) {
            pageContains.value.pageNum -= 1;
          }
          queryPreferences();
        } else {
          errorMessage.value = res.data.error || '删除失败';
          ElMessage.error(errorMessage.value);
        }
      })
      .catch(error => {
        errorMessage.value = '网络请求出错，请稍后重试';
        ElMessage.error(errorMessage.value);
        console.error('删除操作出错:', error);
      })
      .finally(() => {
        loading.value = false;
      });
}

// 关闭对话框
function closeDialog() {
  preferenceDialog.value = false;
  curPreference.value = {};
  // 重置表单验证
  if (preferenceForm.value) {
    preferenceForm.value.resetFields();
  }
}

// 分页处理
const handlePageChange = (pageNum) => {
  pageContains.value.pageNum = pageNum;
  queryPreferences();
};

const handleSizeChange = (pageSize) => {
  pageContains.value.pageSize = pageSize;
  queryPreferences();
};

// 初始化加载
onMounted(() => {
  queryPreferences();
});
</script>

<style scoped>
.customer-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 60vh;
}

.search-container {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.search-input {
  margin-right: 10px;
  width: 200px;
}

.search-button {
  margin-right: 20px;
}

.register-button {
  width: 160px;
  font-weight: bold;
  font-size: 16px;
}

.tip-message {
  margin-bottom: 20px;
}

.error-message {
  margin-bottom: 20px;
}

.customer-table {
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.table-header {
  background-color: #f0f2f5;
  font-weight: bold;
  color: #333;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.pagination {
  width: 100%;
}

.customer-dialog {
  width: 500px;
}

.customer-form {
  width: 100%;
}

.form-item {
  margin-bottom: 22px;
}

.form-input,
.form-select,
.form-date-picker {
  width: 100%;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.dialog-footer {
  text-align: center;
  margin-top: 20px;
}

.dialog-button {
  width: 45%;
  padding: 10px;
  margin: 0 5px;
}

.customer-detail-dialog {
  width: 500px;
}

.customer-detail-form {
  width: 100%;
}

.detail-button {
  margin-right: 10px;
}
</style>